// dao/TicketDAO.java
package main.java.com.cinema.dao;

import main.java.com.cinema.model.Ticket;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class TicketDAO {
    private static final String TICKET_FILE = "tickets.dat";
    
    public List<Ticket> findAll() {
        List<Ticket> tickets = new ArrayList<>();
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(TICKET_FILE))) {
            tickets = (List<Ticket>) ois.readObject();
        } catch (FileNotFoundException e) {
            // 文件不存在，返回空列表
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return tickets;
    }
    
    public Ticket findById(String ticketId) {
        List<Ticket> tickets = findAll();
        for (Ticket ticket : tickets) {
            if (ticket.getId().equals(ticketId)) {
                return ticket;
            }
        }
        return null;
    }
    
    public List<Ticket> findByShowtimeId(String showtimeId) {
        List<Ticket> tickets = findAll();
        List<Ticket> result = new ArrayList<>();
        
        for (Ticket ticket : tickets) {
            if (ticket.getShowtimeId().equals(showtimeId)) {
                result.add(ticket);
            }
        }
        return result;
    }
    
    public boolean save(Ticket ticket) {
        List<Ticket> tickets = findAll();
        tickets.add(ticket);
        return saveAll(tickets);
    }
    
    public boolean update(Ticket ticket) {
        List<Ticket> tickets = findAll();
        for (int i = 0; i < tickets.size(); i++) {
            if (tickets.get(i).getId().equals(ticket.getId())) {
                tickets.set(i, ticket);
                return saveAll(tickets);
            }
        }
        return false;
    }
    
    private boolean saveAll(List<Ticket> tickets) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(TICKET_FILE))) {
            oos.writeObject(tickets);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
